package com.cskaoyan.shiro;

import com.cskaoyan.bean.reverseengineering.MarketAdmin;
import com.cskaoyan.bean.reverseengineering.MarketPermission;
import com.cskaoyan.bean.reverseengineering.MarketPermissionExample;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Charadic
 * @since 2022/05/09 15:53
 */
@Component
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    MarketAdminMapper marketAdminMapper;

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        MarketAdmin marketAdmin = marketAdminMapper.queryByUsername(username);
        String password = marketAdmin.getPassword();
        return new SimpleAuthenticationInfo(username, password, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        MarketAdmin marketAdmin = marketAdminMapper.queryByUsername(username);
        Integer[] roleIds = marketAdmin.getRoleIds();
        MarketPermissionExample marketPermissionExample = new MarketPermissionExample();
        MarketPermissionExample.Criteria criteria = marketPermissionExample.createCriteria();
        criteria.andRoleIdIn(Arrays.asList(roleIds));
        List<String> permissions = new ArrayList<>();
        List<MarketPermission> marketPermissions = marketPermissionMapper.selectByExample(marketPermissionExample);
        for (MarketPermission marketPermission : marketPermissions) {
            permissions.add(marketPermission.getPermission());
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;


    }

}
